package com.hmjk.health.home;

import org.json.JSONException;
import org.json.JSONObject;

import com.hmjk.health.HealthApp;
import com.hmjk.health.R;
import com.hmjk.health.background.DataManager;
import com.hmjk.health.util.DEV_DATA;
import com.hmjk.health.util.DEV_SET;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

public class DeviceManagerEdit extends Activity implements OnClickListener {
	private HealthApp mApp = null;
	private DEV_DATA mDev = null;
	private DEV_SET mData = null;
	
	private ImageButton butBack = null;
	private Button butCommit = null;
	private EditText editName = null, editPhone = null, editRadius = null;
	private ImageView nameErr = null, phoneErr = null, radiusErr = null;
	private TextView phoneTip = null;
	
	private String localName = null, localPhone = null;
	private String phonetmp = "";
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		mApp = (HealthApp)getApplication();
		
		Intent intent =  getIntent();
		
		mDev = (DEV_DATA)intent.getSerializableExtra("dev");
	
		localName = mDev.name;
		
		setContentView(R.layout.dev_manager_edit);
		butBack = (ImageButton)findViewById(R.id.back);
		butBack.setOnClickListener(this);
		butCommit = (Button)findViewById(R.id.commit_but);
		butCommit.setOnClickListener(this);
		
		editName = (EditText)findViewById(R.id.nickedit);
		nameErr = (ImageView)findViewById(R.id.name_err);
		nameErr.setVisibility(View.INVISIBLE);
		editName.setOnFocusChangeListener(new OnFocusChangeListener() {
			
			@Override
			public void onFocusChange(View v, boolean hasFocus) {
				// TODO Auto-generated method stub
				if(hasFocus){
					if(nameErr.getVisibility() == View.VISIBLE){
						nameErr.setVisibility(View.INVISIBLE);
						editName.setText("");
						editName.setTextColor(0xFF444444);
					}
				}else {
					String name = editName.getText().toString();
					if(name.isEmpty()){
						nameErr.setVisibility(View.VISIBLE);
						editName.setText(R.string.Account_empty);
						editName.setTextColor(0xFFFF0000);
					}else{
						nameErr.setVisibility(View.INVISIBLE);
						editName.setTextColor(0xFF444444);
					}
				}
			}
		});
		
		TextView title = (TextView) findViewById(R.id.title);
		phoneTip = (TextView)findViewById(R.id.phonetip);
		if(mDev.admin == 1){
			title.setText(R.string.admin_edit_title);
			View phonelayout = findViewById(R.id.phone_layout);
			phonelayout.setVisibility(View.VISIBLE);
			editPhone = (EditText)findViewById(R.id.phoneedit);
			phoneErr = (ImageView)findViewById(R.id.phone_err);
			phoneErr.setVisibility(View.INVISIBLE);
			
			editPhone.setOnFocusChangeListener(new OnFocusChangeListener() {
				
				@Override
				public void onFocusChange(View v, boolean hasFocus) {
					// TODO Auto-generated method stub
					if(hasFocus){
						if(phoneErr.getVisibility() == View.VISIBLE){
							phoneErr.setVisibility(View.INVISIBLE);
							editPhone.setText(phonetmp);
							editPhone.setSelection(phonetmp.length());
							editPhone.setTextColor(0xFF444444);
						}
					}else {
						String phone = editPhone.getText().toString();
						int len = phone.length();
						if(len == 0){
							phoneErr.setVisibility(View.VISIBLE);
							editPhone.setTextColor(0xFFFF0000);
							phoneTip.setText(R.string.phone_empty);
							phoneTip.setTextColor(0xFFFF0000);
						}else if(len < 11){
							phoneErr.setVisibility(View.VISIBLE);
							editPhone.setTextColor(0xFFFF0000);
							phoneTip.setText(R.string.invalid_phonenum);
							phoneTip.setTextColor(0xFFFF0000);
						}else {
							phoneErr.setVisibility(View.INVISIBLE);
							phoneTip.setText(R.string.phonenum_tip);
							phoneTip.setTextColor(0xFF999999);
							editPhone.setTextColor(0xFF444444);
						}
						phonetmp = phone;
					}
				}
			});
		}else{
			title.setText(R.string.ob_edit_title);
			View phonelayout = findViewById(R.id.phone_layout);
			phonelayout.setVisibility(View.GONE);
			phoneTip.setVisibility(View.GONE);
		}
	
		updateData();
		updateView();
		refreshData();
	}
	
	private void refreshData(){
		
		if(mDev.admin != 1){
			return;
		}
		
		boolean ok = mApp.getDataManager().refreshData(DataManager.F_DEVICE_SETTINGS, mDev.id);
		if(ok){
			mApp.showWaitting(this, null);
		}
	}
	
	private void updateData(){
		if(mDev.admin != 1){
			return;
		}
		
		mData = null;
		
		String[] args = new String[1];
		args[0] = mDev.id;
		
		DEV_SET[] data = (DEV_SET[]) mApp.getDataManager().checkData(DataManager.F_DEVICE_SETTINGS, args);
		if(data != null){
			mData =  data[0];
			
			localPhone = mData.mobile;
		}
	}
	
	private void updateView(){
		//name and mobile
		String name = localName;
		if((name == null) || name.isEmpty()){
			name = getResources().getString(R.string.noName);
		}
		editName.setText(name);
		editName.setSelection(name.length());
		
		if(mDev.admin != 1){
			return;
		}
		
		String phone = localPhone;
		if((phone == null) || phone.isEmpty()){
			phone = "";
		}
		phonetmp = phone;
		editPhone.setText(phone);
		editPhone.setSelection(phone.length());	
		
	}
	
	@Override
	public void onResume(){
		super.onResume();
		IntentFilter filter = new IntentFilter();
		filter.addAction(DataManager.DATA_UPDATE_ACTION);
		filter.addAction(DataManager.DATA_COMMIT_RESULT);
		registerReceiver(mReceiver, filter);

	}
	
	@Override
	public void onPause(){
		super.onPause();
		unregisterReceiver(mReceiver);
		mApp.dismissWaiting();
	}
	
	private BroadcastReceiver mReceiver = new BroadcastReceiver(){
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if(action.equals(DataManager.DATA_UPDATE_ACTION)){
				String t = intent.getStringExtra("type");
				boolean s = intent.getBooleanExtra("state", false);
				
				if(t.equals(DataManager.F_DEVICE_SETTINGS)){
					mApp.dismissWaiting();
					if(s){
						updateData();
						updateView();
					}
				}
			}else if(action.equals(DataManager.DATA_COMMIT_RESULT)){
				String t = intent.getStringExtra("type");
				String tid = intent.getStringExtra("tid");
				if(t.equals(DataManager.F_DEVICELIST) && tid.equals(mDev.id)){
					String state = intent.getStringExtra("state");
					int code = intent.getIntExtra("code", 400);
					mApp.dismissWaiting();
					if(code != 200){
						mApp.showAlertDialog(DeviceManagerEdit.this, R.string.commit_err);
					}else if(state.equals("00") == false){
						mApp.showAlertDialog(DeviceManagerEdit.this, R.string.commit_err);
					}else{
						mApp.showAlertDialog(DeviceManagerEdit.this, getResources().getString(R.string.commit_ok), R.string.ok, new OnClickListener() {
							
							@Override
							public void onClick(View arg0) {
								// TODO Auto-generated method stub
								finish();
							}
						});
					}
				}else if(t.equals(DataManager.F_DEVICE_SETTINGS) && tid.equals(mDev.id)){
					String state = intent.getStringExtra("state");
					int code = intent.getIntExtra("code", 400);
					mApp.dismissWaiting();
					if(code != 200){
						mApp.showAlertDialog(DeviceManagerEdit.this, R.string.commit_err);
					}else if(state.equals("00") == false){
						mApp.showAlertDialog(DeviceManagerEdit.this, R.string.commit_err);
					}else{
						if(localName.equals(mDev.name) == false){
							if(commitName() == false){
								mApp.showAlertDialog(DeviceManagerEdit.this, R.string.commit_err);
							}
						}else{
							mApp.showAlertDialog(DeviceManagerEdit.this, getResources().getString(R.string.commit_ok), R.string.ok, new OnClickListener() {
								@Override
								public void onClick(View arg0) {
									// TODO Auto-generated method stub
									finish();
								}
							});
						}
					}
				}
			}
			
		}
	};

	private boolean checkNameInput(){
		if(nameErr.getVisibility() == View.VISIBLE){
			return false;
		}
		
		String name = editName.getText().toString().trim();
		editName.clearFocus();
		if(name.isEmpty()){
			return false;
		}else {
			localName = name;
		}
		return true;
	}
	
	private boolean checkPhoneInput(){
		if(phoneErr.getVisibility() == View.VISIBLE){
			return false;
		}
		
		String phone = editPhone.getText().toString().trim();
		int len = phone.length();
		editPhone.clearFocus();
		if(len < 11){
			return false;
		}else {
			localPhone = phone;
		}
		return true;
	}
	
	private boolean commitName(){
		boolean ok = false;
		try {
			JSONObject commit = new JSONObject();
			
			commit.put("cmd", "updatename");
			commit.put("tid", mDev.id);
			commit.put("devicename", localName);
			
			ok = mApp.getDataManager().commitData(DataManager.F_DEVICELIST, commit);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return ok;
	}
	
	private void commit(){
		if(mDev.admin != 1){
			//not admin ,commit name only
			if(localName.equals(mDev.name) == false){
				if(commitName() == false){
					mApp.showAlertDialog(DeviceManagerEdit.this, R.string.commit_err);
				}else{
					mApp.showWaitting(this, null);
				}
				return;
			}
			finish();
		}else{
			if(localPhone.equals(mData.mobile)){
				//phone not changed, commit name only 
				if(localName.equals(mDev.name) == false){
					if(commitName() == false){
						mApp.showAlertDialog(DeviceManagerEdit.this, R.string.commit_err);
					}else{
						mApp.showWaitting(this, null);
					}
					return;
				}
				finish();
			}else{
				//phone changed, commit phone firstly
				mApp.showWaitting(this, null);
				commitSetting();
			}
		}
	}
	
	private boolean commitSetting(){
		boolean ok = false;
		try {
			JSONObject commit = new JSONObject();
			
			commit.put("cmd", "setmobile");
			commit.put("tid", mDev.id);
			commit.put("mobile", localPhone);
			
			ok = mApp.getDataManager().commitData(DataManager.F_DEVICE_SETTINGS, commit);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return ok;
	}
	
	@Override
	public void onClick(View v) {
		switch(v.getId()){
		case R.id.back:{
			finish();
		}break;
		
		case R.id.commit_but:{
			
			boolean nameok = true;
			boolean phoneok = true;
			
			nameok = checkNameInput();
			if(mDev.admin == 1){
				phoneok = checkPhoneInput();
			}
			
			if((nameok == false) || (phoneok == false)){
				mApp.showAlertDialog(DeviceManagerEdit.this, R.string.dev_manager_error);
				return;
			}
			
			mApp.showConfirmDialog(this, getResources().getString(R.string.edit_confirm), new OnClickListener() {
				
				@Override
				public void onClick(View view) {
					// TODO Auto-generated method stub
					if(view.getId() == R.id.alert_but1){
						commit();
					}
				}
			});
			
		}break;
		
		}
	}
}
